import { Form, Input, Modal, message } from "antd";
import { useState } from "react";
import { getSftpApi, getToken } from "../utils/client";

export interface RenameModalProps {
    curClientId: string;
    srcPath: string;
    onCancel: () => void;
    onOk: (newPath: string) => void;
}

function RenameModal(props: RenameModalProps) {
    const [newPath, setNewPath] = useState(props.srcPath);

    const reaname = async () => {
        const api = getSftpApi();
        try {
            await api.sftpRenamePost({
                sftpRenamePostRequest: {
                    token: getToken(),
                    id: props.curClientId,
                    srcPath: props.srcPath,
                    destPath: newPath,
                },
            });
            props.onOk(newPath);
        } catch (e) {
            console.log(e);
            message.error("重命名失败");
        }
    }

    return (
        <Modal open title="重命名" okText="修改" okButtonProps={{ disabled: newPath == "" || newPath == props.srcPath }}
            onCancel={e => {
                e.stopPropagation();
                e.preventDefault();
                props.onCancel();
            }}
            onOk={e => {
                e.stopPropagation();
                e.preventDefault();
                reaname();
            }}>
            <Form labelCol={{ span: 4 }}>
                <Form.Item label="当前路径">
                    {props.srcPath}
                </Form.Item>
                <Form.Item label="新路径">
                    <Input value={newPath} onChange={e => {
                        e.stopPropagation();
                        e.preventDefault();
                        setNewPath(e.target.value.trim());
                    }} />
                </Form.Item>
            </Form>
        </Modal>
    );
}

export default RenameModal;